// 对话相关 Mock 数据

import type { Message, Session, SendMessageRequest, SendMessageResponse, CreateSessionResponse } from '@/types/chat';
import type { ApiResponse, GetSessionsResponse, GetSessionDetailResponse } from '@/types/api';
import { generateId } from '@/utils/format';

// 模拟延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

// 模拟会话数据
let mockSessions: Session[] = [
  {
    id: 'session_001',
    title: '关于头痛的咨询',
    messages: [
      {
        id: 'msg_001',
        sessionId: 'session_001',
        role: 'user',
        content: '最近经常头痛，该怎么办？',
        timestamp: Date.now() - 3600000
      },
      {
        id: 'msg_002',
        sessionId: 'session_001',
        role: 'assistant',
        content: '头痛的原因可能有多种。常见的包括：\n\n1. **紧张性头痛**：由压力、焦虑或肌肉紧张引起\n2. **偏头痛**：可能伴随恶心、对光敏感\n3. **睡眠不足**：缺乏充足的休息\n4. **脱水**：身体缺水也会引起头痛\n\n建议您：\n- 保持规律作息\n- 多喝水\n- 适当放松和休息\n- 如果持续严重，建议就医检查',
        timestamp: Date.now() - 3590000
      }
    ],
    createdAt: Date.now() - 3600000,
    updatedAt: Date.now() - 3590000,
    lastMessage: '头痛的原因可能有多种...'
  }
];

// AI 回复模板
const aiResponses = [
  '感谢您的咨询。根据您的描述，我建议您注意以下几点...',
  '这是一个很好的问题。让我为您详细解答...',
  '根据医学研究，这种情况通常是由以下原因引起的...',
  '我理解您的担心。让我为您提供一些专业的建议...'
];

/**
 * Mock 发送消息接口
 */
export const mockSendMessage = async (data: SendMessageRequest): Promise<ApiResponse<SendMessageResponse>> => {
  await delay(1000);

  const session = mockSessions.find(s => s.id === data.sessionId);
  
  if (!session) {
    return {
      code: 404,
      data: null as any,
      message: '会话不存在'
    };
  }

  // 添加用户消息
  const userMessage: Message = {
    id: generateId('msg'),
    sessionId: data.sessionId,
    role: 'user',
    content: data.content,
    timestamp: Date.now(),
    status: 'success'
  };
  
  session.messages.push(userMessage);

  // 模拟AI回复
  await delay(1500);
  
  const aiContent = aiResponses[Math.floor(Math.random() * aiResponses.length)] + 
    '\n\n基于您提到的"' + data.content.substring(0, 20) + '..."，我的建议是：\n\n' +
    '1. 保持良好的生活习惯\n' +
    '2. 注意饮食均衡\n' +
    '3. 适当运动\n' +
    '4. 如有不适请及时就医';

  const aiMessage: Message = {
    id: generateId('msg'),
    sessionId: data.sessionId,
    role: 'assistant',
    content: aiContent,
    timestamp: Date.now(),
    status: 'success'
  };
  
  session.messages.push(aiMessage);
  session.updatedAt = Date.now();
  session.lastMessage = aiContent.substring(0, 50) + '...';

  return {
    code: 200,
    data: {
      messageId: aiMessage.id,
      content: aiMessage.content,
      timestamp: aiMessage.timestamp
    },
    message: '发送成功'
  };
};

/**
 * Mock 获取会话列表接口
 */
export const mockGetSessions = async (): Promise<ApiResponse<GetSessionsResponse>> => {
  await delay(500);

  const sessions = mockSessions.map(s => ({
    id: s.id,
    title: s.title,
    createdAt: s.createdAt,
    updatedAt: s.updatedAt,
    lastMessage: s.lastMessage
  })).sort((a, b) => b.updatedAt - a.updatedAt);

  return {
    code: 200,
    data: { sessions },
    message: '获取成功'
  };
};

/**
 * Mock 获取会话详情接口
 */
export const mockGetSessionDetail = async (sessionId: string): Promise<ApiResponse<GetSessionDetailResponse>> => {
  await delay(500);

  const session = mockSessions.find(s => s.id === sessionId);
  
  if (!session) {
    return {
      code: 404,
      data: null as any,
      message: '会话不存在'
    };
  }

  return {
    code: 200,
    data: {
      session: {
        id: session.id,
        title: session.title,
        messages: session.messages.map(m => ({
          id: m.id,
          role: m.role,
          content: m.content,
          timestamp: m.timestamp
        }))
      }
    },
    message: '获取成功'
  };
};

/**
 * Mock 创建新会话接口
 */
export const mockCreateSession = async (title?: string): Promise<ApiResponse<CreateSessionResponse>> => {
  await delay(300);

  const newSession: Session = {
    id: generateId('session'),
    title: title || '新对话',
    messages: [],
    createdAt: Date.now(),
    updatedAt: Date.now()
  };

  mockSessions.push(newSession);

  return {
    code: 200,
    data: {
      sessionId: newSession.id,
      title: newSession.title,
      createdAt: newSession.createdAt
    },
    message: '创建成功'
  };
};

/**
 * Mock 删除会话接口
 */
export const mockDeleteSession = async (sessionId: string): Promise<ApiResponse<null>> => {
  await delay(300);

  const index = mockSessions.findIndex(s => s.id === sessionId);
  
  if (index === -1) {
    return {
      code: 404,
      data: null,
      message: '会话不存在'
    };
  }

  mockSessions.splice(index, 1);

  return {
    code: 200,
    data: null,
    message: '删除成功'
  };
};